package com.yay.rental.provider;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import model.Comment;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.yay.rental.ui.HomeActivity;

import android.util.Log;


/**
 * Get Started!
 * @author team@getstarted.com.ua
 */
public class CommentsService extends CommentsProvider {
	private static Comment currentComments;
	private String serviceURL;
	public static int rentalId;
	
	public static void setCurrentComment(Comment value) {
		currentComments = value;
	}
	
	public static Comment getCurrentComments() {
		if(currentComments == null) {
			currentComments = new Comment();
		}
		return currentComments;
	}
	
	public String getServiceURL() {
		if(serviceURL == null) { 
			serviceURL = HomeActivity.SERVER_URL + "CommentsDAO.php";
		}
		return serviceURL;
	}
	
	public List<Comment> listComment(int recipe) {
		
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("rental_id", recipe);
		List<Comment> ret = list(params);
		return ret;
	}
	public String numComment(int rental) {
		
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("rental_id", rental);
		String num = numData(params);
		return num;
	}
	
	public String saveComment(String comment, int recipe) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("rental_id", recipe);
		params.put("text", comment);
		params.put("date", new Date());
		String id = saveData(params);
		return id;
	}

	public void remove(Comment ticket) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("id", ticket.getId());
		removeData(params);
	}
	
	public List<Comment> list(Map<String, Object> params) {

		List<Comment> ret = new ArrayList<Comment>();
		String data = listData(params);
		if(data != null) {
			try {
		        JSONArray jArray = new JSONArray(data);
		        for(int i=0; i < jArray.length(); i++) {
		           ret.add(buildTicket(jArray.getJSONObject(i)));
		        }
			} catch(JSONException e) {
	        	Log.e(this.getClass().getName(), e.toString());
			}
		}
		return ret;
	}
	
	private Comment buildTicket(JSONObject jsonObject) throws JSONException {
		Comment coment = new Comment();
		coment.setId(jsonObject.getInt("id"));
		coment.setText(jsonObject.getString("text"));
		coment.setActive(jsonObject.getInt("active"));
        return coment;
	}

}
